package com.sqfw.framework.task;

import com.alibaba.fastjson2.JSONObject;
import com.sqfw.common.enums.system.SysBssSignTypeEnum;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.project.monitor.domain.SysLogininfor;
import com.sqfw.project.monitor.domain.SysOperLog;
import com.sqfw.project.monitor.service.ISysLogininforService;
import com.sqfw.project.monitor.service.ISysOperLogService;
import com.sqfw.project.system.domain.SysBssSign;
import com.sqfw.project.system.service.ISysBssSignService;
import com.sqfw.project.utils.HttpClientUtils;
import com.sqfw.project.utils.bssSign.BssSignUtils;
import com.sqfw.project.utils.tsa.TsaServerUtils;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.mapper.WpInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 密测的签名验签
 *
 * @author tangxt
 */
@Component("bssSignTask")
@Slf4j
public class BssSignTask {

    private final String PORT_8091 = "8091";

    @Value("${server.port}")
    private String port;

    @Value("${bssSign.apiUrl}")
    private String apiUrl;

    @Value("${bssSign.certAlias}")
    private String certAlias;

    private static final String signDataUrl = "/api/svs/bss/signData";

    private static final String verifySignedDataUrl = "/api/svs/bss/verifySignedData";

    @Autowired
    private ISysLogininforService logininforService;

    @Autowired
    private ISysBssSignService sysBssSignService;

    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private ISysOperLogService operLogService;

    @Autowired
    private BssSignUtils bssSignUtils;

    private static final String FILE_PATH = "/file/";

    private static final String CLASS_NAME = "BOOT-INF/classes/com/sqfw/smgp/";

    /**
     * 登录日志进行国密签名
     * 每8个小时执行一次
     * */
    public void jobLogSign() {
        if (!PORT_8091.equals(port)) {
            return;
        }
        SysLogininfor logininfor = new SysLogininfor();
        Map<String, Object> queryMap= new HashMap<>(6);
        Date date = new Date();
        queryMap.put("beginTime", DateUtils.getHourOfDayDateStr(date, -8));
        queryMap.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
        logininfor.setParams(queryMap);
        List<SysLogininfor> logininforList =  logininforService.selectLogininforList(logininfor);
        for (SysLogininfor sysLogininfor :  logininforList) {
            // 查询是否已经签名
            SysBssSign queryBssSign = new SysBssSign();
            queryBssSign.setCorrelationId(sysLogininfor.getInfoId().toString());
            queryBssSign.setDataType(SysBssSignTypeEnum.LOGIN_LOG.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                log.info("该登录日志已经签名了：{}", sysLogininfor.toString());
                 continue;
            }
            String originData = sysLogininfor.toString();
            String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
            Map<String, String> params = new HashMap<>(6);
            params.put("b64OriginData", b64OriginData);
            params.put("certAlias", certAlias);
            log.info("登录日志签名请求参数params： " + params.toString());
            log.info("登录日志签名请求url： " + apiUrl + signDataUrl);
            // 调用接口
            String result = HttpClientUtils.postJson(apiUrl + signDataUrl, params);
            log.info("登录日志签名请求接口返回result: " + result);
            if (StringUtils.isBlank(result)) {
                log.info("登录日志请求签名接口失败");
                return;
            }else {
                JSONObject resJson = JSONObject.parseObject(result);
                // 成功
                if ("0".equals(resJson.getString("errorCode"))) {
                    String b64SignedData = resJson.getString("b64SignedData");
                    String b64Cert = resJson.getString("b64Cert");
                    SysBssSign sysBssSign = new SysBssSign(sysLogininfor.getInfoId().toString(), SysBssSignTypeEnum.LOGIN_LOG.getKey(),
                            originData, b64OriginData, certAlias, b64SignedData, b64Cert);
                    sysBssSignService.insertSysBssSign(sysBssSign);
                }else {
                    log.error("登录日志获取失败：" + resJson.getString("errorCode"));
                }
            }
        }

    }

    /**
     * 登录日志验签
     * 每8个小时执行一次
     * */
    public void jobLogVerifySign() {
        if (!PORT_8091.equals(port)) {
            return;
        }
        SysLogininfor logininfor = new SysLogininfor();
        Map<String, Object> queryMap= new HashMap<>(6);
        Date date = new Date();
        queryMap.put("beginTime", DateUtils.getHourOfDayDateStr(date, -16));
        queryMap.put("endTime", DateUtils.getHourOfDayDateStr(date, -8));
//        queryMap.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
        logininfor.setParams(queryMap);
        List<SysLogininfor> logininforList =  logininforService.selectLogininforList(logininfor);
        log.info("登录日志验证签名查询日志数据：" + logininforList.size());
        // 循环调用接口
        for (SysLogininfor sysLogininfor :  logininforList) {
            SysBssSign sysBssSign = new SysBssSign();
            sysBssSign.setCorrelationId(sysLogininfor.getInfoId().toString());
            sysBssSign.setDataType(SysBssSignTypeEnum.LOGIN_LOG.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(sysBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                SysBssSign bssSign = signs.get(0);
                if (StringUtils.isNotBlank(bssSign.getB64Cert())) {
                    String originData = sysLogininfor.toString();
                    String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
                    // 调用接口
                    Map<String, String> params = new HashMap<>(10);
                    params.put("b64OriginData", b64OriginData);
                    params.put("b64SignedData", bssSign.getB64SignedData());
                    params.put("b64Cert", bssSign.getB64Cert());
                    log.info("登录日志验证签名请求参数params： " + params.toString());
                    log.info("登录日志验证签名请求url： " + apiUrl + verifySignedDataUrl);
                    // 调用接口
                    String result = HttpClientUtils.postJson(apiUrl + verifySignedDataUrl, params);
                    log.info("登录日志验证签名请求接口返回result: " + result);
                    if (StringUtils.isBlank(result)) {
                        log.info("登录日志验证签名请求接口返回失败");
                        return;
                    }else {
                        JSONObject resJson = JSONObject.parseObject(result);
                        // 成功
                        if (!"0".equals(resJson.getString("errorCode"))) {
                            sysBssSignService.updateById(bssSign.getId());
                        }
                    }
                }
            }else {
                log.error("没有登录日志签名信息");
            }
        }
    }


    /**
     * 工单手机号+工单编号签名+身份证号
     * 每3个小时执行一次
     * */
    /**
     * 工单手机号+工单编号签名+身份证号
     * */
    public void jobWpPhoneSign() {
        if (!PORT_8091.equals(port)) {
            return;
        }
        WpInfo queryWpInfo = new WpInfo();
        Date date = new Date();
        queryWpInfo.setBegainTime(DateUtils.getHourOfDayDate(date, -8));
        queryWpInfo.setEndTime(date);
        List<WpInfo> wpInfoList = wpInfoMapper.selectByStarttime(queryWpInfo);
        for (WpInfo wpInfo :  wpInfoList) {
            // 查询是否已经签名
            SysBssSign queryBssSign = new SysBssSign();
            queryBssSign.setCorrelationId(wpInfo.getWpid());
            queryBssSign.setDataType(SysBssSignTypeEnum.WP_PHONE.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                log.info("该工单数据已经签名了：{}", wpInfo.getWpid());
                continue;
            }
            // 手机号+工单编号+身份证，进行签名
            String originData = wpInfo.getPhoneno() + "-" + wpInfo.getWpid();
            // 身份证是否填写：callnum
            if (StringUtils.isNotBlank(wpInfo.getCallnum())) {
                originData = originData + "-" + wpInfo.getCallnum();
            }
            String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
            Map<String, String> params = new HashMap<>(6);
            params.put("b64OriginData", b64OriginData);
            params.put("certAlias", certAlias);
            log.info("工单数据签名请求参数params： " + params.toString());
            log.info("工单数据签名请求url： " + apiUrl + signDataUrl);
            // 调用接口
            String result = HttpClientUtils.postJson(apiUrl + signDataUrl, params);
            log.info("工单数据签名请求接口返回result: " + result);
            if (StringUtils.isBlank(result)) {
                log.info("工单数据签名请求签名接口失败");
                return;
            }else {
                JSONObject resJson = JSONObject.parseObject(result);
                // 成功
                if ("0".equals(resJson.getString("errorCode"))) {
                    String b64SignedData = resJson.getString("b64SignedData");
                    String b64Cert = resJson.getString("b64Cert");
                    SysBssSign sysBssSign = new SysBssSign(wpInfo.getWpid(), SysBssSignTypeEnum.WP_PHONE.getKey(),
                            originData, b64OriginData, certAlias, b64SignedData, b64Cert);
                    sysBssSignService.insertSysBssSign(sysBssSign);
                }else {
                    log.error("工单数据获取失败：" + resJson.getString("errorCode"));
                }
            }
        }
    }

    /**
     * 验证工单手机号+工单id+身份证签名
     * 每3个小时执行一次
     * //        queryWpInfo.setEndTime(date);
     * */
    /**
     * 验证工单手机号+工单id+身份证签名
     * */
    public void jobWpPhoneVerifySign() {
        if (!PORT_8091.equals(port)) {
            return;
        }
        WpInfo queryWpInfo = new WpInfo();
        Date date = new Date();
        queryWpInfo.setBegainTime(DateUtils.getHourOfDayDate(date, -16));
//        queryWpInfo.setEndTime(DateUtils.getHourOfDayDate(date, -8));
        queryWpInfo.setEndTime(date);
        List<WpInfo> wpInfoList = wpInfoMapper.selectByStarttime(queryWpInfo);
        log.info("工单数据验证签名查询日志数据：" + wpInfoList.size());
        // 循环调用接口
        for (WpInfo wpInfo :  wpInfoList) {
            SysBssSign sysBssSign = new SysBssSign();
            sysBssSign.setCorrelationId(wpInfo.getWpid());
            sysBssSign.setDataType(SysBssSignTypeEnum.WP_PHONE.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(sysBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                SysBssSign bssSign = signs.get(0);
                if (StringUtils.isNotBlank(bssSign.getB64Cert())) {
                    // 手机号+工单编号+身份证，进行签名
                    String originData = wpInfo.getPhoneno() + "-" + wpInfo.getWpid();
                    // 身份证是否填写：callnum
                    if (StringUtils.isNotBlank(wpInfo.getCallnum())) {
                        originData = originData + "-" + wpInfo.getCallnum();
                    }
                    String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
                    // 调用接口
                    Map<String, String> params = new HashMap<>(10);
                    params.put("b64OriginData", b64OriginData);
                    params.put("b64SignedData", bssSign.getB64SignedData());
                    params.put("b64Cert", bssSign.getB64Cert());
                    log.info("工单数据验证签名请求参数params： " + params.toString());
                    log.info("工单数据验证签名请求url： " + apiUrl + verifySignedDataUrl);
                    // 调用接口
                    String result = HttpClientUtils.postJson(apiUrl + verifySignedDataUrl, params);
                    log.info("工单数据验证签名请求接口返回result: " + result);
                    if (StringUtils.isBlank(result)) {
                        log.info("工单数据验证签名请求接口返回");
                        return;
                    }else {
                        JSONObject resJson = JSONObject.parseObject(result);
                        // 成功
                        if (!"0".equals(resJson.getString("errorCode"))) {
                            sysBssSignService.updateById(bssSign.getId());
                        }
                    }
                }
            }else {
                log.error("没有工单数据签名信息");
            }
        }
    }


    /**
     * 操作日志进行国密签名
     * 每8个小时执行一次
     * */
    public void jobOperLogSign() {
        if (!PORT_8091.equals(port)) {
            return;
        }
        SysOperLog queryOperLog = new SysOperLog();
        Map<String, Object> queryMap= new HashMap<>(6);
        Date date = new Date();
        queryMap.put("beginTime", DateUtils.getHourOfDayDateStr(date, -8));
        queryMap.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
        queryOperLog.setParams(queryMap);
        List<SysOperLog> sysOperLogs = operLogService.selectOperLogList(queryOperLog);
        for (SysOperLog sysOperLog :  sysOperLogs) {
            // 查询是否已经签名
            SysBssSign queryBssSign = new SysBssSign();
            queryBssSign.setCorrelationId(sysOperLog.getOperId().toString());
            queryBssSign.setDataType(SysBssSignTypeEnum.OPER_LOG.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                log.info("操作日志已经签名了：{}", sysOperLog.toString());
                continue;
            }
            // 操作人员+标题+方法名称+操作时间
            String originData = sysOperLog.getOperName() + "-" + sysOperLog.getTitle() + "-" + sysOperLog.getMethod()
                    + "-" + sysOperLog.getOperTime().toString();
            String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
            Map<String, String> params = new HashMap<>(6);
            params.put("b64OriginData", b64OriginData);
            params.put("certAlias", certAlias);
            log.info("操作日志签名请求参数params： " + params.toString());
            log.info("操作日志签名请求url： " + apiUrl + signDataUrl);
            // 调用接口
            String result = HttpClientUtils.postJson(apiUrl + signDataUrl, params);
            log.info("操作日志签名请求接口返回result: " + result);
            if (StringUtils.isBlank(result)) {
                log.info("操作日志请求签名接口失败");
                return;
            }else {
                JSONObject resJson = JSONObject.parseObject(result);
                // 成功
                if ("0".equals(resJson.getString("errorCode"))) {
                    String b64SignedData = resJson.getString("b64SignedData");
                    String b64Cert = resJson.getString("b64Cert");
                    SysBssSign sysBssSign = new SysBssSign(sysOperLog.getOperId().toString(), SysBssSignTypeEnum.OPER_LOG.getKey(),
                            originData, b64OriginData, certAlias, b64SignedData, b64Cert);
                    sysBssSignService.insertSysBssSign(sysBssSign);
                }else {
                    log.error("操作日志获取失败：" + resJson.getString("errorCode"));
                }
            }
        }

    }

    /**
     * 操作日志验签
     * 每8个小时执行一次
     * */
    public void jobOperLogVerifySign() {
        if (!PORT_8091.equals(port)) {
            return;
        }
        SysOperLog queryOperLog = new SysOperLog();
        Map<String, Object> queryMap= new HashMap<>(6);
        Date date = new Date();
        queryMap.put("beginTime", DateUtils.getHourOfDayDateStr(date, -16));
//        queryMap.put("endTime", DateUtils.getHourOfDayDateStr(date, -8));
        queryMap.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
        queryOperLog.setParams(queryMap);
        List<SysOperLog> sysOperLogs = operLogService.selectOperLogList(queryOperLog);
        log.info("操作日志验证签名查询日志数据：" + sysOperLogs.size());
        // 循环调用接口
        for (SysOperLog sysOperLog :  sysOperLogs) {
            SysBssSign sysBssSign = new SysBssSign();
            sysBssSign.setCorrelationId(sysOperLog.getOperId().toString());
            sysBssSign.setDataType(SysBssSignTypeEnum.OPER_LOG.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(sysBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                SysBssSign bssSign = signs.get(0);
                if (StringUtils.isNotBlank(bssSign.getB64Cert())) {
                    // 操作人员+标题+方法名称+操作时间
                    String originData = sysOperLog.getOperName() + "-" + sysOperLog.getTitle() + "-" + sysOperLog.getMethod()
                            + "-" + sysOperLog.getOperTime().toString();
                    String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
                    // 调用接口
                    Map<String, String> params = new HashMap<>(10);
                    params.put("b64OriginData", b64OriginData);
                    params.put("b64SignedData", bssSign.getB64SignedData());
                    params.put("b64Cert", bssSign.getB64Cert());
                    log.info("操作日志验证签名请求参数params： " + params.toString());
                    log.info("操作日志验证签名请求url： " + apiUrl + verifySignedDataUrl);
                    // 调用接口
                    String result = HttpClientUtils.postJson(apiUrl + verifySignedDataUrl, params);
                    log.info("操作日志验证签名请求接口返回result: " + result);
                    if (StringUtils.isBlank(result)) {
                        log.info("操作日志验证签名请求接口返回失败");
                        return;
                    }else {
                        JSONObject resJson = JSONObject.parseObject(result);
                        // 成功
                        if (!"0".equals(resJson.getString("errorCode"))) {
                            sysBssSignService.updateById(bssSign.getId());
                        }
                    }
                }
            }else {
                log.error("没有操作日志签名信息");
            }
        }
    }

    public void test() {
        TsaServerUtils.req("123456789");
    }

    private void signPassword(String password) {
        bssSignUtils.signData(password, password, SysBssSignTypeEnum.LOGIN_PASSWORD.getKey());
    }

    /**
     * dmlog签名
     * @param fileName 文件名称
     * @param count 截取文件内容数量
     * */
    public void jobDmLogSign(String fileName, Integer count) {
        if (!PORT_8091.equals(port)) {
            return;
        }
        if (StringUtils.isBlank(fileName) && count == null && count == 0) {
            log.info("DMLOG签名-文件名称，截取数量必传");
            return;
        }
        String filePath = System.getProperty("user.dir") + FILE_PATH + fileName;
        log.info("DMLOG签名-文件路径-filePath：{}", filePath);
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            String originData = stringBuffer.toString();
            if (originData.length() > count + 1) {
                originData = originData.substring(0, count);
            }
            log.info("DMLOG签名-原始-originData：{}" , originData);
            String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
            Map<String, String> params = new HashMap<>(6);
            params.put("b64OriginData", b64OriginData);
            params.put("certAlias", certAlias);
            log.info("DMLOG签名请求参数params： " + params.toString());
            log.info("DMLOG签名请求url： " + apiUrl + signDataUrl);
            // 调用接口
            String result = HttpClientUtils.postJson(apiUrl + signDataUrl, params);
            log.info("DMLOG签名请求接口返回result: " + result);
            if (StringUtils.isBlank(result)) {
                log.info("DMLOG请求签名接口失败");
                return;
            }else {
                JSONObject resJson = JSONObject.parseObject(result);
                // 成功
                if ("0".equals(resJson.getString("errorCode"))) {
                    String b64SignedData = resJson.getString("b64SignedData");
                    String b64Cert = resJson.getString("b64Cert");
                    SysBssSign sysBssSign = new SysBssSign(fileName, SysBssSignTypeEnum.DM_LOG.getKey(),
                            originData, b64OriginData, certAlias, b64SignedData, b64Cert);
                    // 查询是否已经签名
                    SysBssSign queryBssSign = new SysBssSign();
                    queryBssSign.setCorrelationId(fileName);
                    queryBssSign.setDataType(SysBssSignTypeEnum.DM_LOG.getKey());
                    List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
                    if (!CollectionUtils.isEmpty(signs)) {
                        sysBssSign.setId(signs.get(0).getId());
                        sysBssSignService.updateSysBssSign(sysBssSign);
                    }else {
                        sysBssSignService.insertSysBssSign(sysBssSign);
                    }
                }else {
                    log.error("DMLOG签名失败：" + resJson.getString("errorCode"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("读取dmlog文件失败-签名：{}", fileName);
        }
    }

    /**
     * DMLOG验证签名
     * @param fileName 文件名称
     * @param count 截取字数
     * */
    public void jobDmLogVerifySign(String fileName, Integer count) {
        if (!PORT_8091.equals(port)) {
            return;
        }
        if (StringUtils.isBlank(fileName) && count == null && count == 0) {
            log.info("DMLOG验签-文件名称，截取数量必传");
            return;
        }
        String filePath = System.getProperty("user.dir") + FILE_PATH + fileName;
        log.info("DMLOG验签-文件路径-filePath：{}", filePath);
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))){
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            String originData = stringBuffer.toString();
            if (originData.length() > count + 1) {
                originData = originData.substring(0, count);
            }
            log.info("DMLOG验签-原始-originData：{}" , originData);
            // 查询是否已经签名
            SysBssSign queryBssSign = new SysBssSign();
            queryBssSign.setCorrelationId(fileName);
            queryBssSign.setDataType(SysBssSignTypeEnum.DM_LOG.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                SysBssSign bssSign = signs.get(0);
                if (StringUtils.isNotBlank(bssSign.getB64Cert())) {
                    String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
                    // 调用接口
                    Map<String, String> params = new HashMap<>(10);
                    params.put("b64OriginData", b64OriginData);
                    params.put("b64SignedData", bssSign.getB64SignedData());
                    params.put("b64Cert", bssSign.getB64Cert());
                    log.info("DMLOG验证签名请求参数params： " + params.toString());
                    log.info("DMLOG验证签名请求url： " + apiUrl + verifySignedDataUrl);
                    // 调用接口
                    String result = HttpClientUtils.postJson(apiUrl + verifySignedDataUrl, params);
                    log.info("DMLOG验证签名请求接口返回result: " + result);
                    if (StringUtils.isBlank(result)) {
                        log.info("DMLOG验证签名请求接口返回失败");
                        return;
                    }else {
                        JSONObject resJson = JSONObject.parseObject(result);
                        // 成功
                        if (!"0".equals(resJson.getString("errorCode"))) {
                            sysBssSignService.updateById(bssSign.getId());
                        }
                    }
                }
            }else {
                log.error("没有DMLOG签名信息: {}", fileName);
            }
        }catch (IOException e) {
            e.printStackTrace();
            log.error("读取DMLOG文件失败-验签：{}", fileName);
        }
    }

    /**
     * jar内容签名
     *
     * */
    public void jobJarDataSign(String fileName, Integer count) {
        if (!PORT_8091.equals(port)) {
            return;
        }
        if (StringUtils.isBlank(fileName) && count == null && count == 0) {
            log.info("JAR签名-文件名称，截取数量必传");
            return;
        }
        String path = System.getProperty("user.dir") + FILE_PATH + fileName;
        log.info("JAR签名-文件路径-path：{}", path);
        try (JarFile jarFile = new JarFile(new File(path));) {
            StringBuffer stringBuffer = new StringBuffer();
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.contains(CLASS_NAME)) {
                    stringBuffer.append(entryName);
                }
            }
            String originData = stringBuffer.toString();
            if (originData.length() > count + 1) {
                originData = originData.substring(0, count);
            }
            log.info("JAR文件名称签名-原始-originData：{}" , originData);
            String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
            Map<String, String> params = new HashMap<>(6);
            params.put("b64OriginData", b64OriginData);
            params.put("certAlias", certAlias);
            log.info("JAR签名请求参数params： " + params.toString());
            log.info("JAR签名请求url： " + apiUrl + signDataUrl);
            // 调用接口
            String result = HttpClientUtils.postJson(apiUrl + signDataUrl, params);
            log.info("JAR签名请求接口返回result: " + result);
            if (StringUtils.isBlank(result)) {
                log.info("JAR请求签名接口失败");
                return;
            }else {
                JSONObject resJson = JSONObject.parseObject(result);
                // 成功
                if ("0".equals(resJson.getString("errorCode"))) {
                    String b64SignedData = resJson.getString("b64SignedData");
                    String b64Cert = resJson.getString("b64Cert");
                    SysBssSign sysBssSign = new SysBssSign(fileName, SysBssSignTypeEnum.JAR_DATA.getKey(),
                            originData, b64OriginData, certAlias, b64SignedData, b64Cert);
                    // 查询是否已经签名
                    SysBssSign queryBssSign = new SysBssSign();
                    queryBssSign.setCorrelationId(fileName);
                    queryBssSign.setDataType(SysBssSignTypeEnum.JAR_DATA.getKey());
                    List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
                    if (!CollectionUtils.isEmpty(signs)) {
                        sysBssSign.setId(signs.get(0).getId());
                        sysBssSignService.updateSysBssSign(sysBssSign);
                    }else {
                        sysBssSignService.insertSysBssSign(sysBssSign);
                    }
                }else {
                    log.error("JAR签名失败：" + resJson.getString("errorCode"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取JAT文件失败-签名：{}", fileName);
        }
    }


    /**
     * jar内容验签
     *
     * */
    public void jobJarDataVerifySign(String fileName, Integer count) {
        if (!PORT_8091.equals(port)) {
            return;
        }
        if (StringUtils.isBlank(fileName) && count == null && count == 0) {
            log.info("JAR验签-文件名称，截取数量必传");
            return;
        }
        String path = System.getProperty("user.dir") + FILE_PATH + fileName;
        log.info("JAR验签-文件路径-path：{}", path);
        try (JarFile jarFile = new JarFile(new File(path));) {
            StringBuffer stringBuffer = new StringBuffer();
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.contains(CLASS_NAME)) {
                    stringBuffer.append(entryName);
                }
            }
            String originData = stringBuffer.toString();
            if (originData.length() > count + 1) {
                originData = originData.substring(0, count);
            }
            log.info("JAR验签-原始-originData：{}" , originData);
            // 查询是否已经签名
            SysBssSign queryBssSign = new SysBssSign();
            queryBssSign.setCorrelationId(fileName);
            queryBssSign.setDataType(SysBssSignTypeEnum.JAR_DATA.getKey());
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                SysBssSign bssSign = signs.get(0);
                if (StringUtils.isNotBlank(bssSign.getB64Cert())) {
                    String b64OriginData = Base64.getEncoder().encodeToString(originData.getBytes());
                    // 调用接口
                    Map<String, String> params = new HashMap<>(10);
                    params.put("b64OriginData", b64OriginData);
                    params.put("b64SignedData", bssSign.getB64SignedData());
                    params.put("b64Cert", bssSign.getB64Cert());
                    log.info("JAR验证签名请求参数params： " + params.toString());
                    log.info("JAR验证签名请求url： " + apiUrl + verifySignedDataUrl);
                    // 调用接口
                    String result = HttpClientUtils.postJson(apiUrl + verifySignedDataUrl, params);
                    log.info("JAR验证签名请求接口返回result: " + result);
                    if (StringUtils.isBlank(result)) {
                        log.info("JAR验证签名请求接口返回失败");
                        return;
                    }else {
                        JSONObject resJson = JSONObject.parseObject(result);
                        // 成功
                        if (!"0".equals(resJson.getString("errorCode"))) {
                            sysBssSignService.updateById(bssSign.getId());
                        }
                    }
                }
            }else {
                log.error("没有JAR签名信息: {}", fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取JAT文件失败-验签：{}", fileName);
        }
    }



}
